/**
 * 手势冲突处理Hook
 * Story 5: Task 7 - 手势冲突处理和桌面端兼容
 */

import { useRef, useCallback } from 'react'

export type GestureType =
  | 'pullRefresh'
  | 'longPress'
  | 'doubleTap'
  | 'drag'
  | 'scroll'

interface GestureState {
  type: GestureType | null
  priority: number
  timestamp: number
}

/**
 * 手势优先级配置
 * 数值越大优先级越高
 */
const GESTURE_PRIORITY: Record<GestureType, number> = {
  drag: 5, // 拖拽最高优先级
  pullRefresh: 4,
  longPress: 3,
  doubleTap: 2,
  scroll: 1, // 滚动最低优先级
}

/**
 * 手势冲突处理Hook
 * 确保同一时间只有一个手势在执行
 */
export const useGestureConflictHandler = () => {
  const currentGestureRef = useRef<GestureState>({
    type: null,
    priority: 0,
    timestamp: 0,
  })

  /**
   * 检查是否可以开始新手势
   */
  const canStartGesture = useCallback((gestureType: GestureType): boolean => {
    const current = currentGestureRef.current
    const newPriority = GESTURE_PRIORITY[gestureType]

    // 没有正在进行的手势
    if (!current.type) {
      return true
    }

    // 新手势优先级更高
    if (newPriority > current.priority) {
      return true
    }

    // 同优先级但超过一定时间（500ms）
    if (newPriority === current.priority && Date.now() - current.timestamp > 500) {
      return true
    }

    return false
  }, [])

  /**
   * 开始手势
   */
  const startGesture = useCallback((gestureType: GestureType) => {
    if (canStartGesture(gestureType)) {
      currentGestureRef.current = {
        type: gestureType,
        priority: GESTURE_PRIORITY[gestureType],
        timestamp: Date.now(),
      }
      return true
    }
    return false
  }, [canStartGesture])

  /**
   * 结束手势
   */
  const endGesture = useCallback((gestureType: GestureType) => {
    if (currentGestureRef.current.type === gestureType) {
      currentGestureRef.current = {
        type: null,
        priority: 0,
        timestamp: 0,
      }
    }
  }, [])

  /**
   * 获取当前手势
   */
  const getCurrentGesture = useCallback(() => {
    return currentGestureRef.current.type
  }, [])

  /**
   * 重置所有手势状态
   */
  const reset = useCallback(() => {
    currentGestureRef.current = {
      type: null,
      priority: 0,
      timestamp: 0,
    }
  }, [])

  return {
    canStartGesture,
    startGesture,
    endGesture,
    getCurrentGesture,
    reset,
  }
}
